import { useMemberStore } from '@/stores'
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
const menberStore = useMemberStore()

//可以理解为Axios创建实例
const httpInterceptor = {
  //请求拦截器
  invoke(option: UniApp.RequestOptions) {
    if (!option.url.startsWith('http')) {
      option.url = baseURL + option.url
    }
    option.timeout = 50000
    option.header = {
      ...option.header,
      'source-client': 'miniapp',
    }
    const token = menberStore.profile?.token
    if (token) {
      option.header.Authorization = token
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: string
  msg: string
  result: T
}

export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((reslove, reject) => {
    uni.request({
      ...options,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          reslove(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          menberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).msg || '数据获取失败',
          })
          reject(res)
        }
      },

      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误',
        })
        reject(err)
      },
    })
  })
}
